package gob.inei.enaho.controller.activity;

import gob.inei.enaho.context.Aplicacion;
import gob.inei.enaho.context.AppContext;
import gob.inei.enaho.context.Preferencias;
import gob.inei.enaho.model.database.EnahoOpenHelper;
import gob.inei.enaho.model.domain.persona.Hogar;
import gob.inei.enaho.model.domain.tiempo.MesEnum;
import gob.inei.enaho.model.domain.tiempo.Periodo;
import gob.inei.enaho.model.domain.ubicacion.Conglomerado;
import gob.inei.enaho.model.domain.ubicacion.Odei;
import gob.inei.enaho.model.service.ConglomeradoService;
import gob.inei.enaho.model.service.DataXmlMarcoService;
import gob.inei.enaho.model.service.OdeiService;
import gob.inei.enaho.model.service.PeriodoService;
import gob.inei.enaho.view.adapters.HomeAdapter;
import gob.inei.enaho2014.R;

import java.util.List;

import util.android.AndroidUtil;
import util.android.adapters.ItemSpinnerAdapter;
import util.android.form.respuesta.deprecated.SpinnerInput;
import util.android.sqlite.SQLiteUtil;
import util.android.widgets.TablaCabeceraFijaView;
import util.form.respuesta.GrupoInput;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;

public class HomeActivity extends ActionBarActivity {
	
	private GrupoInput f = new GrupoInput(null);
	private OdeiService odeiService = AppContext.getServices().getOdeiService();	
	private ConglomeradoService conglomeradoService = AppContext.getServices().getConglomeradoService(); 
	private PeriodoService periodoService = AppContext.getServices().getPeriodoService();
	private DataXmlMarcoService dataXmlMarcoService = AppContext.getServices().getDataXmlMarcoService();
	
	public static Hogar onResumeHogarParaAbrir;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		//AndroidUtil.mostrarToast(this, "oncreate");		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);		
		cargarCombosExceptoConglomerados();	
		
		/*
		NumberPicker np=
				  (NumberPicker) findViewById(R.id.numberPicker1);
				np.setMaxValue(9);
				np.setMinValue(0);
		//np.setWrapSelectorWheel(false);
		np.setOrientation(NumberPicker.VERTICAL);
		*/
		
		this.getActionBar().setSubtitle("MARCO DE VIVIENDAS");
		//this.setTitle("MARCO DE VIVIENDAS");
	}
	
	@Override
	protected void onStart() {
		//AndroidUtil.mostrarToast(this, "onstart");
		super.onStart();		
		//actualizarData();//se ejecuta indirectamente
		cargarConglomerados();
	}
	
	private void cargarCombosExceptoConglomerados() {
		try {		
			AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
				
				@Override				
			    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
					//System.out.println("V="+view+" P="+pos+" id="+view.getId());
					cargarConglomerados();
			    }
			
			    @Override				
			    public void onNothingSelected(AdapterView<?> parent) {				
			    				
			    }
			};
			
			SharedPreferences sp = Preferencias.leerPreferencias(this);
						
			Spinner spn;									
			spn = (Spinner) findViewById(R.id.spnOdei);			
			spn.setAdapter(new ItemSpinnerAdapter<Odei>(this, odeiService.findAll()) {
				@Override
				public String getKey(Odei obj) {
					return obj.getCodigo();
				}
				@Override
				public String getLabel(Odei obj) {
					return obj.getCodigo()+" "+obj.getNombre();
				}			
			});			
			spn.setOnItemSelectedListener(listener);			
			f.agregar("odei",new SpinnerInput(spn).setValor(sp.getString(Preferencias.ODEI, null)));
			
			spn = (Spinner) findViewById(R.id.spnAnho);			
			spn.setAdapter(new ItemSpinnerAdapter<Integer>(this, dataXmlMarcoService.findAnhos()) {
				@Override
				public String getKey(Integer obj) {
					return obj+"";
				}
				@Override
				public String getLabel(Integer obj) {
					return obj+"";
				}				
			});
			spn.setOnItemSelectedListener(listener);
			f.agregar("anho",new SpinnerInput(spn).setValor(sp.getString(Preferencias.ANHO, null)));
			
			spn = (Spinner) findViewById(R.id.spnMes);			
			spn.setAdapter(new ItemSpinnerAdapter<MesEnum>(this, MesEnum.values()) {
				@Override
				public String getKey(MesEnum obj) {
					return obj.getCodigoString();
				}
				@Override
				public String getLabel(MesEnum obj) {
					return obj.getCodigoString() + " " + obj.getNombre();
				}				
			});	
			spn.setOnItemSelectedListener(listener);
			f.agregar("mes",new SpinnerInput(spn).setValor(sp.getString(Preferencias.MES, null)));
			
			spn = (Spinner) findViewById(R.id.spnPeriodo);			
			spn.setAdapter(new ItemSpinnerAdapter<Periodo>(this, periodoService.findAll()) {
				@Override
				public String getKey(Periodo obj) {
					return obj.getCodigo();
				}
				@Override
				public String getLabel(Periodo obj) {
					return obj.getNombre();
				}				
			});	
			spn.setOnItemSelectedListener(listener);
			f.agregar("periodo",new SpinnerInput(spn).setValor(sp.getString(Preferencias.PERIODO, null)));
		
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void cargarConglomerados() {
		try {
			AdapterView.OnItemSelectedListener listenerConglomerado = new AdapterView.OnItemSelectedListener() {
				@Override				
				public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
					//System.out.println("Conglome V="+view+" P="+pos);
					actualizarData();
				}
				
				@Override				
				public void onNothingSelected(AdapterView<?> parent) {				
					
				}
			};
			
			Spinner spn = (Spinner) findViewById(R.id.spnConglomerado);		
			
			List<Conglomerado> lista = conglomeradoService.findByFilter(f.getRegistro());
			
			spn.setAdapter(new ItemSpinnerAdapter<Conglomerado>(this, lista) {
				@Override
				public String getKey(Conglomerado obj) {
					return obj.getCodigo();
				}			
				@Override
				public String getLabel(Conglomerado obj) {
					return obj.getEtiquetaAreaPanel();
				}				
			}.agregar(0,"","(Todos)") );
			spn.setOnItemSelectedListener(listenerConglomerado);
			
			SharedPreferences sp = Preferencias.leerPreferencias(this);
			f.agregar("conglomerado",new SpinnerInput(spn).setValor(sp.getString(Preferencias.CONGLOMERADO, null)));
		} catch (Exception e) {
			AndroidUtil.mostrarExcepcionEnToast(getBaseContext(), e);
		}
	}
	
	private void actualizarData() {
		listarMarco();		
	}
	
	private void listarMarco() {
		try {
			guardarConfiguracion();		
		
			//AndroidUtil.mostrarToast(this, f.getRegistro().toJSON());		
		
			TablaCabeceraFijaView tabla = (TablaCabeceraFijaView) findViewById(R.id.tabla);		
					
			List<Hogar> lista = AppContext.getServices().getHogarService().findReporteHome(f.getRegistro());
			tabla.setAdapter(new HomeAdapter(this,lista));
			
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
	@Override
    public void onResume() {
		TablaCabeceraFijaView tabla = (TablaCabeceraFijaView) findViewById(R.id.tabla);
		if(tabla.getAdapter()!=null) {			
			tabla.getAdapter().onResumeActivity();
		}
		
		super.onResume();
	}


	private void guardarConfiguracion() throws Exception {
		SharedPreferences sharedPref = Preferencias.leerPreferencias(this);
		SharedPreferences.Editor editor = sharedPref.edit();
		
		editor.putString(Preferencias.CONGLOMERADO,f.findValor("conglomerado"));
		editor.putString(Preferencias.ODEI,f.findValor("odei"));
		editor.putString(Preferencias.ANHO,f.findValor("anho"));
		editor.putString(Preferencias.MES,f.findValor("mes"));
		editor.putString(Preferencias.PERIODO,f.findValor("periodo"));
		
		editor.commit();		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.home, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		switch(id) {
		case R.id.marco:
			AndroidUtil.abrirActivity(this, CargarMarcoActivity.class);
			//Intent i = new Intent(this,CargarMarcoActivity.class);
			//this.startActivity(i);
			return true;	
		case R.id.backup:
			SQLiteOpenHelper helper = new EnahoOpenHelper(Aplicacion.getAplicacion());
			try {
				SQLiteUtil.copyDatabaseToSdCard(
						helper, 
						this.getBaseContext(), 
						AppContext.DIR_BACKUP, 
						EnahoOpenHelper.DATABASE_NAME, 
						true);
			} catch (Exception e) {
				AndroidUtil.mostrarExcepcionEnToast(getBaseContext(), e);
			}
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
